<template>
  <div class="edit-photo">
    <img :src="imgUrl" alt="" ref="img" />
    <div class="nav-bar">
      <span class="btn" @click="$emit('close')">取消</span>
      <span class="btn" @click="submit">确定</span>
    </div>
  </div>
</template>
<script>
import { updateUserPhoto } from "@/api/user";
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
export default {
  data() {
    return {
      cropper: null
    };
  },
  props: {
    imgUrl: {
      type: String,
      required: true
    }
  },
  mounted() {
    this.cropper = new Cropper(this.$refs.img, {
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    });
  },
  methods: {
    submit() {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        const fd = new FormData();
        fd.append("photo", blob);
        this.$toast.loading("更新中");
        try {
          let { data: res } = await updateUserPhoto(fd);
          this.$toast.success("更新头像成功");
          this.$emit("close", res.data.photo);
        } catch (error) {
          this.$toast.fail("更新头像失败");
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.edit-photo {
  height: 100vh;
  img {
    max-width: 100%;
  }
  .nav-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100px;
    display: flex;
    justify-content: space-between;
    .btn {
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      color: #fff;
    }
  }
}
</style>
